; (function ($) {
    var printAction = {};
    var socket = null;
    var defaultPrinter = null;
    var printedCallback = null;
    var orders = null;


    $("#btn-batprtordtest").on("click", function () {
        var idList = "";
        var checkedOrder=$('.inner-order-list').find('.mt1:checked');
        console.log(orderList)
        var list = [];
        if (checkedOrder.length <= 0) {
            ShowMsg('请选择您需要打印的发货单', false);
            return;
        }
        console.log($('.inner-order-list').find('.mt1').val())
        $('.inner-order-list').find('.mt1:checked').each(function (i,item) {
            var val = $(item).val();
            console.log(val)
            orderList.forEach(function (v) {
                if (val.substring(0, val.indexOf("-")) == v.Id) {
                    list.push(v);
                }
            })
        })
        list.forEach(function (item) {
            var TotalCost = 0;
        })       
        var ordersInfos = list;
        orders = ordersInfos;

        $.caiinaoWaybillPrintTest(ordersInfos);

    });
    $.doGetPrinters = function () {
        var request = {
            requestID: getUUID(10, 10),
            version: "1.0",
            cmd: "getPrinters"
        };
        send(JSON.stringify(request));
    }


    $.caiinaoWaybillPrint = function () {

        if (defaultPrinter == null || defaultPrinter == undefined || defaultPrinter == "") {
            $.showError("请选择打印机");
        }
        //loading = $.showLoading();
        var data = createPrintData(orders);
        console.log("111");
        console.log(JSON.stringify(data));
        send(JSON.stringify(data));
    }

    $.caiinaoWaybillPrintTest = function (orders) {

        var data = createPrintData(orders);              
        send(JSON.stringify(data));
    }
    function createPrintData(orders) {
        if (defaultPrinter == null || defaultPrinter == undefined) {
            //alert(2)
            $.doGetPrinters();
            return;
        }
        //注释
        
        var task = {};
        task.taskID = getUUID(8, 10);
        task.preview = false;
        task.previewType = "pdf";
        task.printer = defaultPrinter;
        task.notifyMode = "allInOne";
        //task.firstDocumentNumber = 10;
        //task.totalDocumentCount = 100;
        task.documents = [];
        $(orders).each(function (index, element) {
            var document = createDocument(element);
            task.documents.push(document);
        });

        var printData = {};
        printData.cmd = "print";
        printData.requestID = getUUID(10, 10);
        printData.version = "1.0";
        printData.task = task;

        return printData;
    }

    function createDocument(order) {
        var document = {};
        document.documentID = order.Id;
        document.contents = [];
        document.contents.push(createCustomerTemplete(order));       
        return document;
    }

    function createCustomerTemplete(order) {
        var customerTemplete = {};
        customerTemplete.templateURL = "http://xkdsaas.oss-cn-shanghai.aliyuncs.com/system/StoreAdmin/config/18007.json?12662";
        $(order.Items).each(function (index, element) {
            var zname = "";
            
            zname = element.Product.Name;

            if (element.Product.SkuName != null && element.Product.SkuName != "" && element.Product.SkuName.length > 0) {
                zname += "[" + element.Product.SkuName + "]";///所有商品加入规格值
            }
            element.ZName = zname;
        });
        order.MerchantName = MerchantStoreName;//店铺名称
        order.MerchantPage = MerchantHomePage;//商家主页
        order.MerchantQr = MerchantQr;//二维码，可为空
        customerTemplete.data = order;
        return customerTemplete;
    }

    function getUUID(len, radix) {
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
        var uuid = [], i;
        radix = radix || chars.length;
        if (len) {
            for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
        } else {
            var r;
            uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
            uuid[14] = '4';
            for (i = 0; i < 36; i++) {
                if (!uuid[i]) {
                    r = 0 | Math.random() * 16;
                    uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                }
            }
        }
        return uuid.join('');
    }

    function doConnect() {
        if ('WebSocket' in window) {
            socket = new WebSocket("ws://127.0.0.1:13528");
        }
        else {
            alert('当前浏览器不支持websocket');
            return false;
        }

        socket.onopen = function (event) {
            console.log("Websocket准备就绪,连接到客户端成功");
        };

        // 监听消息
        socket.onmessage = function (event) {
            console.log('接收消息', event);
            var data = JSON.parse(event.data);
            if ("getPrinters" == data.cmd) {
                //打印机列表
                var printerList = data.printers;
                if (data.defaultPrinter != undefined && data.defaultPrinter != null && data.defaultPrinter != "") {
                    defaultPrinter = data.defaultPrinter;
                }
                createPrintList(printerList);
            }
            else if ("notifyPrintResult" == data.cmd) {
                var waybillCodes = [];
                $(data.printStatus).each(function (index, element) {
                    //已打印的运单号
                    waybillCodes.push(element.documentID);
                });
                if (printedCallback != undefined && printedCallback != null && typeof printedCallback === "function") {
                    printedCallback(waybillCodes);
                }
                //if (loading != null && loading != undefined) {
                //    loading.close();
                //}

            }
            else {
                console.log("返回数据:" + JSON.stringify(data));
            }
        };

        // 监听Socket的关闭
        socket.onclose = function (event) {
            console.log('关闭socket', event);
        };

        socket.onerror = function (event) {
            var html = '';
            html = `<div class="modal fade" id="PrintInvoiceError">
            <div class="modal-dialog" style="width: 400px;">
                <div class="modal-content form-horizontal">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">×</span>
                        </button>
                        <h4 class="modal-title">小票打印</h4>
                    </div>
                    <div class="modal-body">
                        <p>
                            您还没有安装菜鸟打印组件，请先下载安装后重试。
                        </p>
                        <p>                           
                            <a target="_blank" href="http://cloudprint-docs-resource.oss-cn-shanghai.aliyuncs.com/download.html" class ="main-color" style="text-decoration: underline;margin-left:20px;color:#35C2AF">下载菜鸟打印组件</a>
                        </p>
                    </div>
                    <div class="modal-footer">
                        <button class="btn btn-default" data-dismiss="modal" data-op="close">关闭</button>
                    </div>
                </div>
            </div>
        </div>`;
            if ($("#PrintInvoiceError").length <= 0) {
                //$("#invoices").remove();
                $("body").append(html);
            }
            $('#PrintInvoiceError').modal('toggle');
        };
        return true;
    }

    this.send = function (message, callback) {
        console.log("send1");
        console.log(message);
        if (socket == null) {
            if (!doConnect()) {
                return;
            }
        }
        this.waitForConnection(function () {
            socket.send(message);
            if (typeof callback !== 'undefined') {
                callback();
            }
        }, 1000);
    };

    this.waitForConnection = function (callback, interval) {
        if (socket.readyState === 1) {
            callback();
        } else if (socket.readyState === 3) {
            $('#PrintInvoiceError').modal('show');
        }
        else{
            var that = this;
            // optional: implement backoff for interval here  
            setTimeout(function () {
                that.waitForConnection(callback, interval);
            }, interval);
        }
    };

    function createPrintList(printerList) {              
        var option = '',html='';
        $(printerList).each(function (index, element) {
            option += '<div class="check mb15">';
            if (defaultPrinter == element.name) {
                option += '<option class="styled mr5 vmiddle" checked="checked"  type="radio" name="printCheck" value="' + element.name + '">' + element.name + '</option>';
            }
            else {
                option += '<option class="styled mr5 vmiddle" type="radio" name="printCheck" value="' + element.name + '">' + element.name + '</option>';
            }
        });
        html = `<div class="modal fade" id="invoices">
            <div class="modal-dialog">
                <div class="modal-content form-horizontal">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">×</span>
                        </button>
                        <h4 class="modal-title">小票打印</h4>
                    </div>
                    <div class="modal-body">
                        <div style="height:94px;background-color:#f7f7f7;text-align: center;padding: 20px 0;box-sizing: border-box; ">
                            <label for="radiostyled1" class ="checklabel">小票打印机选择：</label>
                            <select style="width: 409px;height: 32px;background-color: #ffffff;border-radius: 2px;border: solid 1px #e6e6e6; ">
                               ${
                               option
                                 }
                            </select>                           
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button class="btn btn-default" data-dismiss="modal" data-op="close">关闭</button>
                        <button class ="btn btn-primary" ng-click="linkTaskCenter()" id="btnPrintCainiaoWaybill">确认打印</button>
                    </div>
                </div>
            </div>
        </div>`;       
        if ($("#invoices").length <= 0) {
            //$("#invoices").remove();
            $("body").append(html);
        }
        //$("#printSelect").modal();
        $("#invoices").modal("show");
        //if (loading != null && loading != undefined) {
        //    loading.close();
        //}

        $("#btnPrintCainiaoWaybill").on("click", function () {
            $("#invoices").modal("hide");
            $.caiinaoWaybillPrint();
        });

    }

    function createComprisonFunctionDesc(propertyName) {
        return function (object1, object2) {
            var value1 = object1[propertyName];
            var value2 = object2[propertyName];

            if (value1 > value2) {
                return -1;
            } else if (value1 < value2) {
                return 1;
            } else {
                return 0;
            }
        }
    }

})(jQuery);